package com.lock;

import java.util.concurrent.TimeUnit;


/**
 * synchronized
 * 1. 在static方法中，锁的对象是类的Class对象，即Phone.class
 * 2. 在非static方法中，锁的对象是当前对象，即this
 * static 方法与非static方法的锁互不影响
 *
 * @author xidner
 * @date 2024/02/16
 */
public class SynchronizedDemo {
	public static void main(String[] args) {

		Phone phone = new Phone();

		new Thread(() -> phone.sendMessage(), "A").start();

		new Thread(() -> phone.call(), "B").start();

	}
}

class Phone {

	public synchronized void sendMessage() {
		System.out.println(Thread.currentThread().getName() + " == sendMessage");
		try {
			TimeUnit.SECONDS.sleep(5);
		} catch (InterruptedException e) {
			throw new RuntimeException(e);
		}
		System.out.println(Thread.currentThread().getName() + "sendMessage 结束");
	}

	public synchronized void call() {
		System.out.println(Thread.currentThread().getName() + " == call");
		try {
			TimeUnit.SECONDS.sleep(1);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().getName() + " == call()");
	}

}
